import { removeRouteList } from '@/router/index'
import { useRouterList } from '@/stores/modules/routerList'
import { useUserInfo } from '@/stores/modules/userInfo'
export function times(data: number, flag = 0) {
  // let data = "8029775.01";
  const time = Number(data)
  const d = Math.floor(time / 86400)
  let h: number | string = Math.floor((time % 86400) / 3600)
  let m: number | string = Math.floor(((time % 86400) % 3600) / 60)
  const s = ((time % 86400) % 3600) % 60
  if (flag === 1) {
    // 把超过时的转为时
    d > 0 && (h += d * 24)
    return (h ? h + '时' : '') + (m ? m + '分' : '') + (s ? s + '秒' : '')
  } else if (flag === 2) {
    d > 0 && (h += d * 24)
    m = m < 10 ? '0' + m : m
    h = h < 10 ? '0' + h : h
    return (h ? h : '') + (m ? ':' + m : '') + (s ? ':' + s : '')
  }
  return (d > 0 ? d + '天' : '') + (h ? h + '时' : '') + (m ? m + '分' : '') + (s ? s + '秒' : '')
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(
  time: number | Date | string,
  cFormat: string = '{y}-{m}-{d} {h}:{i}:{s}'
) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key: string) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

export const changeByte = (byte: number) => {
  let size = ''
  if (byte < 1 * 1024) {
    // 小于1KB，则转化成B
    size = `${byte.toFixed(2)}B`
  } else if (byte < 1 * 1024 * 1024) {
    // 小于1MB，则转化成KB
    size = `${(byte / 1024).toFixed(2)}KB`
  } else if (byte < 1 * 1024 * 1024 * 1024) {
    // 小于1GB，则转化成MB
    size = `${(byte / (1024 * 1024)).toFixed(2)}MB`
  } else if (byte < 1 * 1024 * 1024 * 1024 * 1024) {
    // 小于1TB，则转化成GB
    size = `${(byte / (1 * 1024 * 1024 * 1024)).toFixed(2)}GB`
  } else {
    // 其他转化成TB
    size = `${(byte / (1024 * 1024 * 1024 * 1024)).toFixed(2)}TB`
  }

  const sizeStr = `${size}` // 转成字符串
  const index = sizeStr.indexOf('.') // 获取小数点处的索引
  const dou = sizeStr.substr(index + 1, 2) // 获取小数点后两位的值
  // eslint-disable-next-line eqeqeq
  if (dou == '00') {
    // 判断后两位是否为00，如果是则删除00
    return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
  }
  return size
}

export const changebyte = (byte: number) => {
  let size = ''
  if (byte < 1 * 1024) {
    // 小于1KB，则转化成B
    size = `${byte.toFixed(2)}b`
  } else if (byte < 1 * 1024 * 1024) {
    // 小于MB，则转化成KB
    size = `${(byte / 1024).toFixed(2)}Kb`
  } else if (byte < 1 * 1024 * 1024 * 1024) {
    // 小于1GB，则转化成MB
    size = `${(byte / (1024 * 1024)).toFixed(2)}Mb`
  } else if (byte < 1 * 1024 * 1024 * 1024 * 1024) {
    // 小于1TB，则转化成GB
    size = `${(byte / (1 * 1024 * 1024 * 1024)).toFixed(2)}G`
  } else {
    // 其他转化成TB
    size = `${(byte / (1024 * 1024 * 1024 * 1024)).toFixed(2)}Tb`
  }

  const sizeStr = `${size}` // 转成字符串
  const index = sizeStr.indexOf('.') // 获取小数点处的索引
  const dou = sizeStr.substr(index + 1, 2) // 获取小数点后两位的值
  // eslint-disable-next-line eqeqeq
  if (dou == '00') {
    // 判断后两位是否为00，如果是则删除00
    return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
  }
  return size
}

/**
 *
 * 获取
 */
export function curTime() {
  //获取当前时间
  // eslint-disable-next-line no-var
  var date: string | any = new Date()
  let month: number | any = date.getMonth() + 1
  let strDate: number | any = date.getDate()
  month = month < 10 ? '0' + month : month
  if (strDate >= 0 && strDate <= 9) {
    strDate = '0' + strDate
  }
  let getTimes: string | number =
    date.getFullYear() +
    '-' +
    month +
    '-' +
    strDate +
    ' ' +
    date.getHours() +
    ':' +
    date.getMinutes() +
    ':' +
    date.getSeconds()

  // eslint-disable-next-line no-var
  var date: string | any = new Date(getTimes)
  const time3 = Date.parse(date) //只能精确到秒，毫秒用000替代
  getTimes = Number(time3 / 1000)
  return getTimes
}

export function timePicker(time: number, flag = false, string = false) {
  let timeSu = null
  if (string) {
    timeSu = new Date(time).valueOf()
  } else {
    timeSu = time
  }
  let length = (timeSu + '').length
  const times = new Date(length > 10 ? timeSu : timeSu * 1000)
  let date = !flag
    ? `${times.getFullYear()}-${
        times.getMonth() < 10 ? '0' + (times.getMonth() + 1) : times.getMonth() + 1
      }-${times.getDate() < 10 ? '0' + times.getDate() : times.getDate()}${' '}${
        times.getHours() < 10 ? '0' + times.getHours() : times.getHours()
      }:${times.getMinutes() < 10 ? '0' + times.getMinutes() : times.getMinutes()}:${
        times.getSeconds() < 10 ? '0' + times.getSeconds() : times.getSeconds()
      }`
    : `${times.getFullYear()}-${
        times.getMonth() < 10 ? '0' + (times.getMonth() + 1) : times.getMonth() + 1
      }-${times.getDate() < 10 ? '0' + times.getDate() : times.getDate()}`
  return date
}

/**
 * execCommand 方法复制
 * @param text 复制文本
 */
const fallbackCopyTextToClipboard = (text: string) => {
  // 1.创建一个可选中元素
  let textArea = document.createElement('textarea')
  textArea.value = text
  // 2.使用定位，阻止页面滚动
  textArea.style.top = '0'
  textArea.style.left = '0'
  textArea.style.position = 'fixed'
  document.body.appendChild(textArea)
  textArea.focus()
  textArea.select()
  try {
    var successful = document.execCommand('copy')
    var msg = successful ? 'successful' : 'unsuccessful'
    console.log('Fallback: Copying text command was ' + msg)
  } catch (err) {
    console.error('Fallback: Oops, unable to copy', err)
  }
  // 3.移除元素
  document.body.removeChild(textArea)
}
/**
 * navigator 方法复制 兼任
 * @param text 复制文本
 */
export function copyTextToClipboard(text: string) {
  if (!navigator.clipboard) {
    fallbackCopyTextToClipboard(text)
    return
  }
  navigator.clipboard.writeText(text).then(
    function () {
      console.log('Async: Copying to clipboard was successful!')
    },
    function (err) {
      console.error('Async: Could not copy text: ', err)
    }
  )
}
export const getTimeRangeTimestamp = (range: string) => {
  const now = new Date()
  now.setHours(0, 0, 0, 0) // 设置为当天的 00:00:00
  const startTimestamp = now.getTime()

  switch (range) {
    case 'day':
      const nowTime = new Date()
      return [startTimestamp, Math.floor(nowTime.getTime() / 1000) * 1000 - 1000] // 当天的 00:00:00 到 当时
    case 'dayAll':
      const endTimestamp = new Date(
        now.getFullYear(),
        now.getMonth(),
        now.getDate(),
        23,
        59,
        59
      ).getTime()
      return [startTimestamp, endTimestamp] // 当天的 00:00:00 到 23:59:59
    case 'today':
      const yesterday = new Date(startTimestamp - 24 * 60 * 60 * 1000)
      yesterday.setHours(0, 0, 0, 0) // 设置为昨天的 00:00:00
      return [yesterday.getTime(), startTimestamp - 1000] // 昨天的 00:00:00 到 23:59:59
    case 'toweek':
      return [startTimestamp - 6 * 24 * 60 * 60 * 1000, startTimestamp + 24 * 60 * 60 * 1000 - 1000] // 7天前的 00:00:00 到 当天的 23:59:59
    case 'tomonth':
      return [
        startTimestamp - 29 * 24 * 60 * 60 * 1000,
        startTimestamp + 24 * 60 * 60 * 1000 - 1000
      ] // 30天前的 00:00:00 到 当天的 23:59:59
    default:
      return null
  }
}
export const loginOut = (): void => {
  useRouterList().removeCacheList()
  useUserInfo().removeUserInfo()
  removeRouteList()
}
